package com.huweilong.tingshu.servlet.track;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huweilong.tingshu.repository.TrackRepo;
import com.huweilong.tingshu.util.Log;
import com.huweilong.tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author 是阿秋啊
 * @date 2022/07/20 20:32
 **/
@WebServlet("/studio/track/upload.do")
// 要接收enctype==multipart/formdata 的 form表单数据，必须使用@MultipartConfig修饰
// 忘记修饰就会出现500，提示没有修饰
@MultipartConfig
public class UploadDoServlet extends HttpServlet {
    private final TrackRepo trackRepo = new TrackRepo();
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.先判断用户有没有登录
        UserVO userVO = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            userVO = (UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        if (userVO == null) {
            Log.println("UploadDoServlet用户未登录");
            resp.sendRedirect("/studio/user/login.html");
            return;
        }

        // 此时说明已经登录
        Log.println("UploadDoServlet用户登录："+userVO);

        // 2.从请求获取数据
        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        Log.println("获取到的title是" + title);

        Part track = req.getPart("track");
        String type = track.getContentType();
        Log.println("获取到的type是"+type);
        InputStream contentInputStream = track.getInputStream();
        // 3.将拿到的数据插入到数据库表中,操作比较简单，不引用service。直接在trackRepo中操作
        trackRepo.insert(userVO.uid,title,type,contentInputStream);
        Log.println("上传成功");
        // 4. 打印响应成功
        resp.sendRedirect("/studio/track/list.html");
    }
}